//
//  CycleView.m
//  NSURLSession轮播练习
//
//  Created by Feng on 2017/7/9.
//  Copyright © 2017年 feng. All rights reserved.
//

#import "CycleView.h"
//#import "NetworkTool.h"
#import "CycleModel.h"
#import "CycleFlowLayout.h"
#import "CycleCell.h"
#import <Masonry.h>

#define RGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]

#define RandomColor RGBColor(arc4random_uniform(255), arc4random_uniform(255), arc4random_uniform(255))

@interface CycleView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,weak) UIPageControl *pageControl;
@property(nonatomic,assign) NSInteger currentPage;

@end

static NSString *cellID = @"cellID";

@implementation CycleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //加载网络数据
//        [self loadData];
        //设置collectionView
        [self setupCycleView];
    }
    return self;
}

////绘制
////封装后因为因为在初始化的时候,还没有数据,所以直接滚动会有问题
////一启动就让collectionView滚动到第1组第0张
//- (void)drawRect:(CGRect)rect
//{
//    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:1];
//    
//    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//}

#pragma mark --代理方法-> 当手动拖拽时,画面完全停止之后,会执行此方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //实现页面到第0组或者第2组的某个item的时候,就跳到第1组(中间组)的item上
    NSInteger imageCount = _collectionView.contentOffset.x / _collectionView.bounds.size.width;
    
    NSInteger imageSection = imageCount / _dataArray.count;
    NSInteger imageItem = imageCount % _dataArray.count;
    
    //如果是中间组,就直接返回
    if(imageSection == 1)
    {
        return;
    }
    
    //跳转到中间组
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:imageItem inSection:1];
    
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

#pragma mark --代理方法->代码方法实现页面滚动,并且开启滚动,页面停下来,调用此方法一次
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self scrollViewDidEndDecelerating:scrollView];
}

#pragma mark -- 代理方法-> 当手动拖拽时
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //给一个"遥远的未来"时间,相当于暂停了计时器
    _timer.fireDate = [NSDate distantFuture];
}

#pragma mark -- 代理方法-> 当手动拖拽结束时
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    //让计时器间隔2秒执行
    _timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2.0];
}

#pragma mark -- 创建计时器
- (void)createTimer
{
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    _timer = timer;
}

#pragma mark -- 计时器的监听事件
- (void)nextPage
{
    //获取当前的页数
    NSInteger pageNum = _pageControl.currentPage;
    
    NSIndexPath *indexPath;
    
    //判断下一页
    //如果是最后一页,就跳转到下一组的第一页
    //如果不是最后一页.就跳转到本组的下一页
    if(pageNum == _dataArray.count - 1)
    {
        indexPath = [NSIndexPath indexPathForItem:0 inSection:2];
    }
    else
    {
        indexPath = [NSIndexPath indexPathForItem:pageNum + 1 inSection:1];
    }
    
    [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

#pragma mark --设置分页指示器
- (void)setupPageControlWithPageCount:(NSInteger)pageCount
{
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    
    [self addSubview:pageControl];
    
    _pageControl = pageControl;
    
    pageControl.numberOfPages = pageCount;
    
    pageControl.currentPage = _currentPage;
    
    pageControl.pageIndicatorTintColor = [UIColor grayColor];
    
    pageControl.currentPageIndicatorTintColor = [UIColor orangeColor];
    
    [pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.equalTo(self.mas_centerX);
        
        make.top.equalTo(_collectionView.mas_bottom).offset(-30);
        
        make.width.offset(100);
        
        make.height.offset(20);
        
    }];
}

#pragma mark --设置轮播器
- (void)setupCycleView
{
    CycleFlowLayout *flowLayout = [CycleFlowLayout new];
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 200) collectionViewLayout:flowLayout];
    collectionView.backgroundColor = [UIColor orangeColor];
    _collectionView = collectionView;
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    [collectionView registerClass:[CycleCell class] forCellWithReuseIdentifier:cellID];
    
    [self addSubview:collectionView];
}

#pragma mark --设置CycleView和分页指示器的联动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = _collectionView.contentOffset.x / _collectionView.bounds.size.width + 0.4999;
    
    _pageControl.currentPage = page % _dataArray.count;
}

#pragma mark --设置数据源方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CycleCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    cell.backgroundColor = RandomColor;
    cell.model = self.dataArray[indexPath.item];
    
    return cell;
}
#pragma mark --加载数据
//- (void)loadData
//{
//    NSString *urlStr = @"http://client.waimai.baidu.com/shopui/na/v1/cliententry?da_ext=&msgcuid=&return_type=launch&net_type=wifi&aoi_id=&taste=&address=&screen=320x568&sortby=&cuid=3D0A8678-18DC-4447-9611-13A411B1FCF9&hot_fix=1&uuid=C99F87B1-9588-443D-8BBA-D5DAE3CB57E1&alipay=1&sv=4.4.1&isp=46001&channel=appstore&loc_lng=13538713.207818&resid=1001&from=na-iphone&request_time=1487663910624&model=iPhone6%2C2&count=20&lng=&idfa=8EFD4589-EDD2-4958-A717-9AF218CBC152&page=1&os=10.0.2&lat=&loc_lat=3615772.560023&promotion=&city_id=&vmgdb=&jailbreak=0&device_name=%E9%BB%91%E9%A9%AC%E7%A8%8B%E5%BA%8F%E5%91%98";
//    
//    [CycleModel loadDataWithURLString:urlStr andSuccess:^(NSArray *imageDataArray) {
//        
//        self.dataArray = imageDataArray;
//        NSLog(@"%@",imageDataArray);
//        //刷新collectionView
//        [_collectionView reloadData];
//        //创建pageControl
//        [self setupPageControlWithPageCount:imageDataArray.count];
//        //启动计时器
//        [self createTimer];
//        
//        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:1];
//        
//        [_collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
//        
//    } andFailure:^(NSError *error) {
//        
//        NSLog(@"error = %@",error);
//    }];
//}

@end
